/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : my_privacy.js                            
*  Description  : 마이페이지 개인정보수정
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-07-09  김효순    Created.  
*******************************************************************************/

jQuery(function($){
	// 이름
	function clsName()
	{
		this._HTMLDom = null;
		this.valueData = null;
		
		this._init();
	}
	
	clsName.prototype = {
		_init: function(){
			var $layer = $("div#container tr:eq(0)");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			this.setValue("");
		}
		, setValue: function(thisData){
			this.valueData = thisData;
			this.display();
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("td").html(this.valueData);
		}
	}
	
	// 성별
	function clsGender()
	{
		this._HTMLDom = null;
		this.valueData = null;
		
		this._init();
	}
	
	clsGender.prototype = {
		_init: function(){
			var $layer = $("div#container tr:eq(1)");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			this.setValue("");
		}
		, setValue: clsName.prototype.setValue
		, display: clsName.prototype.display
	}
	
	// 아이디
	function clsId()
	{
		this._HTMLDom = null;
		this.valueData = null;
		
		this._init();
	}
	
	clsId.prototype = {
		_init: function(){
			var $layer = $("div#container tr:eq(2)");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			this.setValue("");
		}
		, setValue: clsName.prototype.setValue
		, display: clsName.prototype.display
	}
	
	// 비밀번호
	function clsPasswd()
	{
		this._HTMLDom = null;
		this._ERRMSG = {
			"DIFFER": "비밀번호와 비밀번호 확인이 일치하지 않습니다."
			, "INVALID": "비밀번호는 4~12이하 영문 또는 숫자만 가능합니다."
		}
		this.$errObj = null;
		this.errMsg = null;
		
		this._init();
	}
	
	clsPasswd.prototype = {
		_init: function(){
			var $layer = $("div#container").find("tr:eq(3), tr:eq(4)");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			$layer.find("input:text").after("<input type='password' class='" + $layer.find("input:text").attr("class") + "'>").remove();
			
			$layer.find("input:password").attr("maxLength", 12);
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, getError: function(){
			if(!this.errMsg) return null;
			else{
				return this._ERRMSG[this.errMsg];
			}
		}
		, valid: function(){
			var $layer = this._HTMLDom["$layer"];
			var reg = /^[a-zA-Z0-9]{1,12}$/i;
			
			this.errMsg = null;
			if(this.getValue() && !reg.test(this.getValue())){
				this.errMsg = "INVALID";
				this.$errObj = $layer.find("input:password").eq(0);
				return false;
			}else if(this.getValue() != $layer.find("input:password").eq(1).val()){
				this.errMsg = "DIFFER";
				this.$errObj = $layer.find("input:password").eq(1);
				return false;
			}
			
			return true;
		}
		, getValue: function(){
			var $layer = this._HTMLDom["$layer"];
			
			return $layer.find("input:password").eq(0).val();
		}
		, focus: function(){
			var $layer = this.$getLayer();
			
			if(this.$errObj) this.$errObj.trigger("focus");
			else $layer.find("input:password").eq(0).trigger("focus");
		}
	}
	
	// 닉네임
	function clsNick()
	{
		this._HTMLDom = null;
		this._ERRMSG = {
			"NOVALUE": "닉네임을 입력해주세요."
			, "NOCHECK": "닉네임 중복확인을 해주세요."
			, "INVALID": "닉네임은 2~6 이하만 가능합니다."
		}
		this.errMsg = null;
		this.checkNick = null;
		
		this._init();
	}
	
	clsNick.prototype = {
		_init: function(){
			var $layer = $("div#container tr:eq(5)");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			$layer.find("input:text").attr("maxLength", 6);
		}
		, $getLayer: clsPasswd.prototype.$getLayer
		, getError: clsPasswd.prototype.getError
		, valid: function(){
			var $layer = this._HTMLDom["$layer"];
			var val = $layer.find("input:text").val();
			
			this.errMsg = null;
			if(!this.getValue()){
				this.errMsg = "NOVALUE";
				return false;
			}else if(this.getValue().length < 2 || this.getValue().length > 6){
				this.errMsg = "INVALID";
				return false;
			}else if(this.checkNick != val){
				this.errMsg = "NOCHECK";
				return false;
			}
			
			return true;
		}
		, getValue: function(){
			var $layer = this._HTMLDom["$layer"];
			
			return $layer.find("input:text").val();
		}
		, focus: function(){
			this._HTMLDom["$layer"].find("input:text").trigger("focus");
		}
		, setCheck: function(val){
			this.checkNick = val;
		}
		, setValue: function(val){
			this._HTMLDom["$layer"].find("input:text").val(val);
			this.setCheck(val);
		}
	}
	
	// 이메일
	function clsEmail()
	{
		this._HTMLDom = null;
		this._ERRMSG = {
			"NOVALUE": "이메일을 입력해주세요."
			, "INVALID": "정상적인 이메일주소가 아닙니다."
			, "NOCHECK": "이메일 중복체크를 해주십시요."
		}
		this.errMsg = null;
		this.$errObj = null;
		this.checkEmail = null;
		
		this._init();
	}
	
	clsEmail.prototype = {
		_init: function(){
			var $layer = $("div#container tr:eq(6)");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			var e = [
				{
					"이메일": ""
					, "텍스트": "직접입력"
				}
			].concat(_gf.getEmailList());
			
			this._setList(e);
		}
		, _setList: function(thisData){
			var $layer = this._HTMLDom["$layer"];
			var thisClass = this;

			this._listData = thisData;
			
			$layer.find("select").empty();
			for(var i=0;i<this._listData.length;i++){
				$layer.find("select").append("<option />");
			}
			$layer.find("option").each(function(n){
				$(this).text(thisClass._listData[n]["텍스트"]);
			});
		}
		, $getLayer: clsPasswd.prototype.$getLayer
		, getError: clsPasswd.prototype.getError
		, valid: function(){
			var $layer = this._HTMLDom["$layer"];
			var regs = {
				"reg0": /^[\w\-\.]+$/i
				, "reg1": /^(?:(?:[\w\-]+\.)+[a-zA-Z]{2,})$/i
			}
			
			this.errMsg = null;
			this.$errObj = null;
			
			for(var i=0;i<$layer.find("input:text").length;i++){
				if(!this.getValue(i)){
					this.errMsg = "NOVALUE";
					this.$errObj = $layer.find("input:text").eq(i);
					return false;
				}else if(!regs["reg" + i].test(this.getValue(i))){
					this.errMsg = "INVALID";
					this.$errObj = $layer.find("input:text").eq(i);
					return false;
				}
			}
			
			if(this.checkEmail != this.getValue()){
				this.errMsg = "NOCHECK";
				return false;
			}
			
			
			return true;
		}
		, selectEmail: function(){
			var $layer = this._HTMLDom["$layer"];
			var n = $layer.find("option").index($layer.find("option:selected"));
			$layer.find("input:text:eq(1)").val(this._listData[n]["이메일"]);
			
			if(n == 0) $layer.find("input:text:eq(1)").trigger("focus");
		}
		// 이벤트 및 정보메일 수신
		, getYNReceive: function(){
			var $layer = this._HTMLDom["$layer"];
			
			if($layer.find("input:checkbox").is(":checked")) return "Y";
			else return "N";
		}
		, setYNReceive: function(val){
			var $layer = this._HTMLDom["$layer"];
			
			if(val == "Y") $layer.find("input:checkbox").attr("CHECKED", "CHECKED");
		}
		, getYNReceive: function(){
			return this._HTMLDom["$layer"].find("input:checkbox").is(":checked");
		}
		, getValue: function(n){
			var $layer = this._HTMLDom["$layer"];
			
			if(n ==0 || n) return $layer.find("input:text").eq(n).val();
			else return $layer.find("input:text:eq(0)").val() + "@" + $layer.find("input:text:eq(1)").val()
		}
		, focus: function(){
			if(this.$errObj) this.$errObj.trigger("focus");
			else this.$getLayer().find("input:text:eq(0)").trigger("focus");
		}
		, setCheck: function(val){
			this.checkEmail = val;
		}
		, setValue: function(val){
			var $layer = this._HTMLDom["$layer"];
			var a = val.split("@");
			
			$layer.find("input:text").each(function(n){
				$(this).val(a[n]);
			});
			
			this.setCheck(val);
		}
	}
	
	// 휴대폰
	function clsPhone()
	{
		this._HTMLDom = null;
		this._ERRMSG = {
			"NOVALUE": "휴대폰 번호를 입력해 주십시요."
			, "NOTELECOM": "통신사를 선택해 주십시요."
			, "INVALID": "정상적인 휴대폰 번호가 아닙니다."
		}
		this._teleList = null;
		this._phoneList = null;
		this.errMsg = null;
		this.$errObj = null;
		
		this._init();
	}
	
	clsPhone.prototype = {
		_init: function(){
			var $layer = $("div#container tr:eq(7)");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			this._setTeleList([
				"통신사선택", "KT", "SKT", "LGT"
			]);
			
			this._setPhoneList([
				"010", "011", "017", "018", "019"
			]);
			
			$layer.find("input:text").attr("maxLength", 4);
		}
		, _setTeleList: function(thisData){
			var $layer = this._HTMLDom["$layer"];
			var thisClass = this;
			
			this._teleList = thisData;
			$layer.find("select:eq(0)").empty();
			for(var i=0;i<this._teleList.length;i++){
				$layer.find("select:eq(0)").append("<option />");
			}
			$layer.find("select:eq(0) option").each(function(n){
				$(this).text(thisClass._teleList[n].replace("LGT", "LG유플러스"));
			});
		}
		, _setPhoneList: function(thisData){
			var $layer = this._HTMLDom["$layer"];
			var thisClass = this;
			
			this._phoneList = thisData;
			$layer.find("select:eq(1)").empty();
			for(var i=0;i<this._phoneList.length;i++){
				$layer.find("select:eq(1)").append("<option />");
			}
			$layer.find("select:eq(1) option").each(function(n){
				$(this).text(thisClass._phoneList[n]);
			});
		}
		, $getLayer: clsPasswd.prototype.$getLayer
		, getError: clsPasswd.prototype.getError
		, valid: function(){
			var $layer = this._HTMLDom["$layer"];
			var reg = /^[0-9]{3,4}$/i;
			
			this.errMsg = null;
			this.$errObj = null;
			
			if(!this.getTeleValue()){
				this.errMsg = "NOTELECOM";
				this.$errObj = $layer.find("select");
				return false;
			}
			
			for(var i=0;i<$layer.find("input:text").length;i++){
				if(!this.getValue(i)){
					this.errMsg = "NOVALUE";
					this.$errObj = $layer.find("input:text").eq(i);
					return false;
				}else if(!reg.test(this.getValue(i))){
					this.errMsg = "INVALID";
					this.$errObj = $layer.find("input:text").eq(i);
					return false;
				}
			}
			
			return true;
		}
		, getTeleValue: function(){
			var $layer = this._HTMLDom["$layer"];
			
			var n = $layer.find("select option").index($layer.find("select option:selected"));
			
			if(n == 0) return "";
			else return this._teleList[n];
		}
		, getValue: function(n){
			var $layer = this._HTMLDom["$layer"];
			
			if(n == 0 || n){
				return $layer.find("input:text").eq(n).val();
			}else{
				var a = $layer.find("select:eq(1) option").index($layer.find("select:eq(1) option:selected"));
				
				return this._phoneList[a] + "-" + $layer.find("input:text:eq(0)").val() + "-" + $layer.find("input:text:eq(1)").val()
			}
		}
		, focus: function(){
			if(this.$errObj) this.$errObj.trigger("focus");
			else this._HTMLDom["$layer"].find("select").trigger("focus");
		}
		, setValue: function(val){
			var $layer = this._HTMLDom["$layer"];
			var a = val.split("-");
			
			for(var i=0;i<this._phoneList.length;i++){
				if(this._phoneList[i] == a[0]) break;
			}
			
			if(i<this._phoneList.length){
				$layer.find("select:eq(1) option").eq(i).prop("selected", true);
			}
			
			$layer.find("input:text").each(function(n){
				$(this).val(a[n+1]);
			});
		}
		, setTeleValue: function(val){
			var $layer = this._HTMLDom["$layer"];
			var n = $.inArray(val, this._teleList);
			
			if(n != -1) $layer.find("select:eq(0) option").eq(n).attr("SELECTED", "SELECTED");
		}
	}
	
	// 조인룸초대 수신여부
	function clsJoinroomYN()
	{
		this._HTMLDom = null;
		
		this._init();
	}
	
	clsJoinroomYN.prototype = {
		_init: function(){
			var $layer = $("div#container tr:eq(8)");
			this._HTMLDom = {
				"$layer": $layer
			}
		}
		, getValue: function(){
			var $layer = this._HTMLDom["$layer"];
			var n = $layer.find("input:radio").index($layer.find("input:radio:checked"));
			
			var szRet = "";
			switch(n){
				case 0:
					szRet = "Y";
					break;
				case 1:
					szRet = "N";
					break;
			}
			
			return szRet;
		}
		, setValue: function(val){
			var $layer = this._HTMLDom["$layer"];
			var n = -1;
			
			switch(val){
				case "Y":
					n = 0;
					break;
				case "N":
					n = 1;
					break;
			}
			
			$layer.find("input:radio").eq(n).attr("CHECKED", "CHECKED");
		}
	}
	
	// 서버통신
	function clsComm()
	{
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){

		}
		// 회원정보 수정
		, submit: function(arg){
			var thisClass = this;
			
			//ajax
			var serviceName = "update";
			var options = {
				"pw": arg["비밀번호"]
				, "email": arg["이메일"]
				, "phonenum": arg["휴대폰"]
				, "userType": 1
				, "nickname": arg["닉네임"]
				, "sex": arg["성별"]
				, "emailreceiveYn": arg["정보메일수신여부"]
				, "authYn": "N"
				, "userLevel": "A"
				, "telInc": arg["통신사"]
				, "invitereceiveYn": arg["조인룸초대수신여부"]
			}
			_gf.ajax({
				"sid": "US001"
				, "servicename": serviceName
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
				}
				
				document.objControl.finishSubmit(res);
			});
		}
		// 이메일 중복체크
		, emailCheck: function(arg){
			var thisClass = this;
			
			//ajax
			var serviceName = "checkEmailDuplication";
			var options = {
				"email": arg["이메일"]
			}
			_gf.ajax({
				"sid": "US001"
				, "servicename": serviceName
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "이메일": arg["이메일"]
				}
				
				document.objControl.finishEmailCheck(res);
			});
		}
	}
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objName = null;
		this.objGender = null;
		this.objId = null;
		this.objPasswd = null;
		this.objNick = null;
		this.objEmail = null;
		this.objPhone = null;
		this.objJoinroomYN = null;
		
		this.checkAuth = null;
		
		this._permitStart = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload();
			
			this.objComm = new clsComm();
			this.objName = new clsName();
			this.objGender = new clsGender();
			this.objId = new clsId();
			this.objPasswd = new clsPasswd();
			this.objNick = new clsNick();
			this.objEmail = new clsEmail();
			this.objPhone = new clsPhone();
			this.objJoinroomYN = new clsJoinroomYN();
			
			this._beforeStart();
			this._bind();
			
		}
		, _preload: function(){
			_gf.spinStart();
			
			this.checkAuth = _util.getCookie("check_auth");
			_util.delCookie("check_auth", "/");
			
			if(this.checkAuth != "Y"){
				document.location.href = _ROOT + "/mypage/my_info_pw.html";
				return;
			}
		}
		, _beforeStart: function(){
			var thisClass = this;
			
			this._permitStart = {
				
			}
			
			
			$.ajax({
				url: _ROOT + "/js/mypage_common.js"
				, dataType: "script"
				, async: false
				, success: function(){
					
				}
				, error: function(){
					alert("error");
				}
			});
			
			_util.executeThread(function(){
				for(key in thisClass._permitStart){
					if(!thisClass._permitStart[key]) return false;
				}
				
				return (_gf.getMyInfoData());
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
		}
		, _bind: function(){
			var thisClass = this;
			
			// 등록
			$("div#container").on("click", "img[alt='수정완료'], img[alt='취소']", function(){
				var bName = $(this).attr("alt");
				
				switch(bName){
					case "수정완료":
						if(!thisClass.objPasswd.valid()){
							alert(thisClass.objPasswd.getError());
							thisClass.objPasswd.focus();
							return;
						}else if(!thisClass.objNick.valid()){
							alert(thisClass.objNick.getError());
							thisClass.objNick.focus();
							return;
						}else if(!thisClass.objEmail.valid()){
							alert(thisClass.objEmail.getError());
							thisClass.objEmail.focus();
							return;
						}else if(!thisClass.objPhone.valid()){
							alert(thisClass.objPhone.getError());
							thisClass.objPhone.focus();
							return;
						}
						
						_gf.spinStart();
						thisClass.objComm.submit({
							"비밀번호": thisClass.objPasswd.getValue()
							, "닉네임": thisClass.objNick.getValue()
							, "이메일": thisClass.objEmail.getValue()
							, "정보메일수신여부": (thisClass.objEmail.getYNReceive() ? "Y": "N")
							, "통신사": thisClass.objPhone.getTeleValue()
							, "휴대폰": thisClass.objPhone.getValue()
							, "조인룸초대수신여부": thisClass.objJoinroomYN.getValue()
						});
						break;
					case "취소":
						thisClass.goMyHomePage();
						break;
				}
			});
			
			// 닉네임 중복체크
			this.objNick.$getLayer().on("click", "img[alt='중복확인']", function(){
				var winNickCheck = window.open(_ROOT + "/popup/id_check.html?q_type=nick", "winNickCheck", "width=500, height=500, scrollbars=no");
				if(winNickCheck) winNickCheck.focus();
			});
			
			// 이메일 선택
			this.objEmail.$getLayer().on("change", "select", function(){
				thisClass.objEmail.selectEmail();
			});
			
			// 이메일 중복체크
			this.objEmail.$getLayer().on("click", "img[alt='중복확인']", function(){
				thisClass.objComm.emailCheck({
					"이메일": thisClass.objEmail.getValue()
				});
			});
			
			// 휴대폰 번호 숫자만입력
			this.objPhone.$getLayer().on("keyup change", "input:text", function(){
				var thisVal = $(this).val();
				var reVal = thisVal.replace(/\D/g, "");
				
				if(thisVal != reVal) $(this).val(reVal);
			});
		}
		, _start: function(){
			var myInfo = _gf.getMyInfoData();
			
			this.objName.setValue(myInfo["이름"]);
			this.objGender.setValue(myInfo["성별"]);
			this.objId.setValue(myInfo["아이디"]);
			this.objNick.setValue(myInfo["닉네임"]);
			this.objEmail.setValue(myInfo["이메일"]);
			this.objPhone.setTeleValue(myInfo["통신사"]);
			this.objPhone.setValue(myInfo["휴대폰"]);
			this.objEmail.setYNReceive(myInfo["정보메일수신여부"]);
			this.objJoinroomYN.setValue(myInfo["조인룸초대수신여부"]);
		}
		// 중복체크로부터 사용하기
		, returnCheck: function(w, q_type, val){
			if(w) w.close();
			
			var obj = null;
			
			switch(q_type){
				case "id":
					obj = this.objId;
					break;
				case "nick":
					obj = this.objNick;
					break;
			}
			
			obj.setValue(val);
			obj.setCheck(val);
		}
		// 중복체크 오픈시 초기값 전송
		, getValue: function(q_type){
			switch(q_type){
				case "id":
					return this.objId.getValue()
					break;
				case "nick":
					return this.objNick.getValue();
					break;
			}
		}
		// 수정 완료
		, finishSubmit: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			_util.setCookie("check_auth", "Y", null, "/");
			document.location.reload();
		}
		// 이메일 중복체크 완료
		, finishEmailCheck: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			this.objEmail.setCheck(ret["이메일"]);
		}
		// 메인 이동
		, goMyHomePage: function(){
			var szLink = _ROOT + "/mypage/my_home.html";
			document.location.href = szLink;
		}
	}
	
	document.objControl = new clsControl();
	document.objControl._init();
});
